# 后端服务稳定性测试脚本
# PowerShell脚本，用于测试服务的各项稳定性功能

param(
    [string]$BaseUrl = "http://localhost:5000",
    [int]$TestDuration = 300,  # 测试持续时间（秒）
    [int]$RequestInterval = 5   # 请求间隔（秒）
)

Write-Host "=== 后端服务稳定性测试 ===" -ForegroundColor Green
Write-Host "基础URL: $BaseUrl" -ForegroundColor Yellow
Write-Host "测试持续时间: $TestDuration 秒" -ForegroundColor Yellow
Write-Host "请求间隔: $RequestInterval 秒" -ForegroundColor Yellow
Write-Host ""

# 测试结果统计
$TestResults = @{
    HealthCheck = @{ Success = 0; Failed = 0 }
    DetailedHealth = @{ Success = 0; Failed = 0 }
    ReadyCheck = @{ Success = 0; Failed = 0 }
    LiveCheck = @{ Success = 0; Failed = 0 }
    GcTrigger = @{ Success = 0; Failed = 0 }
}

# 测试函数
function Test-Endpoint {
    param(
        [string]$Url,
        [string]$Method = "GET",
        [string]$Name
    )
    
    try {
        $response = if ($Method -eq "GET") {
            Invoke-RestMethod -Uri $Url -Method GET -TimeoutSec 30
        } else {
            Invoke-RestMethod -Uri $Url -Method POST -TimeoutSec 30
        }
        
        Write-Host "[$(Get-Date -Format 'HH:mm:ss')] ✓ $Name - 成功" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "[$(Get-Date -Format 'HH:mm:ss')] ✗ $Name - 失败: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# 详细健康检查测试
function Test-DetailedHealth {
    param([string]$BaseUrl)
    
    try {
        $response = Invoke-RestMethod -Uri "$BaseUrl/api/Health/detailed" -Method GET -TimeoutSec 30
        
        Write-Host "[$(Get-Date -Format 'HH:mm:ss')] 详细健康检查结果:" -ForegroundColor Cyan
        Write-Host "  应用状态: $($response.applicationHealth.isHealthy)" -ForegroundColor White
        Write-Host "  内存使用: $($response.applicationHealth.memoryUsageMB) MB" -ForegroundColor White
        Write-Host "  数据库状态: $($response.databaseHealth.isHealthy)" -ForegroundColor White
        Write-Host "  密码更新服务: $($response.passwordUpdateService.isHealthy)" -ForegroundColor White
        
        return $true
    }
    catch {
        Write-Host "[$(Get-Date -Format 'HH:mm:ss')] ✗ 详细健康检查失败: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# 压力测试
function Start-StressTest {
    param(
        [string]$BaseUrl,
        [int]$Duration,
        [int]$Interval
    )
    
    $startTime = Get-Date
    $endTime = $startTime.AddSeconds($Duration)
    
    Write-Host "开始压力测试..." -ForegroundColor Yellow
    
    while ((Get-Date) -lt $endTime) {
        # 基础健康检查
        if (Test-Endpoint -Url "$BaseUrl/api/Health" -Name "基础健康检查") {
            $TestResults.HealthCheck.Success++
        } else {
            $TestResults.HealthCheck.Failed++
        }
        
        Start-Sleep -Seconds 1
        
        # 详细健康检查
        if (Test-DetailedHealth -BaseUrl $BaseUrl) {
            $TestResults.DetailedHealth.Success++
        } else {
            $TestResults.DetailedHealth.Failed++
        }
        
        Start-Sleep -Seconds 1
        
        # 就绪检查
        if (Test-Endpoint -Url "$BaseUrl/api/Health/ready" -Name "就绪检查") {
            $TestResults.ReadyCheck.Success++
        } else {
            $TestResults.ReadyCheck.Failed++
        }
        
        Start-Sleep -Seconds 1
        
        # 存活检查
        if (Test-Endpoint -Url "$BaseUrl/api/Health/live" -Name "存活检查") {
            $TestResults.LiveCheck.Success++
        } else {
            $TestResults.LiveCheck.Failed++
        }
        
        # 每10次循环触发一次GC
        if (($TestResults.HealthCheck.Success + $TestResults.HealthCheck.Failed) % 10 -eq 0) {
            Start-Sleep -Seconds 1
            if (Test-Endpoint -Url "$BaseUrl/api/Health/gc" -Method "POST" -Name "手动GC") {
                $TestResults.GcTrigger.Success++
            } else {
                $TestResults.GcTrigger.Failed++
            }
        }
        
        Start-Sleep -Seconds $Interval
        
        # 显示进度
        $elapsed = (Get-Date) - $startTime
        $remaining = $endTime - (Get-Date)
        Write-Host "[进度] 已运行: $([math]::Round($elapsed.TotalSeconds))s, 剩余: $([math]::Round($remaining.TotalSeconds))s" -ForegroundColor Magenta
    }
}

# 生成测试报告
function Show-TestReport {
    Write-Host ""
    Write-Host "=== 测试报告 ===" -ForegroundColor Green
    Write-Host ""
    
    foreach ($test in $TestResults.Keys) {
        $success = $TestResults[$test].Success
        $failed = $TestResults[$test].Failed
        $total = $success + $failed
        $successRate = if ($total -gt 0) { [math]::Round(($success / $total) * 100, 2) } else { 0 }
        
        Write-Host "$test:" -ForegroundColor Cyan
        Write-Host "  成功: $success" -ForegroundColor Green
        Write-Host "  失败: $failed" -ForegroundColor Red
        Write-Host "  总计: $total" -ForegroundColor White
        Write-Host "  成功率: $successRate%" -ForegroundColor Yellow
        Write-Host ""
    }
    
    # 计算总体成功率
    $totalSuccess = ($TestResults.Values | ForEach-Object { $_.Success } | Measure-Object -Sum).Sum
    $totalFailed = ($TestResults.Values | ForEach-Object { $_.Failed } | Measure-Object -Sum).Sum
    $totalRequests = $totalSuccess + $totalFailed
    $overallSuccessRate = if ($totalRequests -gt 0) { [math]::Round(($totalSuccess / $totalRequests) * 100, 2) } else { 0 }
    
    Write-Host "总体统计:" -ForegroundColor Green
    Write-Host "  总请求数: $totalRequests" -ForegroundColor White
    Write-Host "  总成功数: $totalSuccess" -ForegroundColor Green
    Write-Host "  总失败数: $totalFailed" -ForegroundColor Red
    Write-Host "  总体成功率: $overallSuccessRate%" -ForegroundColor Yellow
    
    # 评估结果
    if ($overallSuccessRate -ge 95) {
        Write-Host "\n✓ 服务稳定性测试通过！" -ForegroundColor Green
    } elseif ($overallSuccessRate -ge 80) {
        Write-Host "\n⚠ 服务稳定性一般，建议检查配置" -ForegroundColor Yellow
    } else {
        Write-Host "\n✗ 服务稳定性较差，需要立即检查" -ForegroundColor Red
    }
}

# 检查服务是否可访问
function Test-ServiceAvailability {
    param([string]$BaseUrl)
    
    Write-Host "检查服务可用性..." -ForegroundColor Yellow
    
    try {
        $response = Invoke-RestMethod -Uri "$BaseUrl/api/Health" -Method GET -TimeoutSec 10
        Write-Host "✓ 服务可访问" -ForegroundColor Green
        return $true
    }
    catch {
        Write-Host "✗ 服务不可访问: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "请确保服务正在运行并且URL正确" -ForegroundColor Yellow
        return $false
    }
}

# 主执行流程
try {
    # 检查服务可用性
    if (-not (Test-ServiceAvailability -BaseUrl $BaseUrl)) {
        exit 1
    }
    
    Write-Host ""
    Write-Host "开始稳定性测试..." -ForegroundColor Green
    Write-Host "按 Ctrl+C 可随时停止测试" -ForegroundColor Yellow
    Write-Host ""
    
    # 执行压力测试
    Start-StressTest -BaseUrl $BaseUrl -Duration $TestDuration -Interval $RequestInterval
    
    # 显示测试报告
    Show-TestReport
    
    Write-Host "\n测试完成！" -ForegroundColor Green
}
catch {
    Write-Host "\n测试过程中发生错误: $($_.Exception.Message)" -ForegroundColor Red
    Show-TestReport
}
finally {
    Write-Host "\n感谢使用稳定性测试脚本！" -ForegroundColor Cyan
}

# 使用示例：
# .\test_stability.ps1
# .\test_stability.ps1 -BaseUrl "http://localhost:8080" -TestDuration 600 -RequestInterval 3